package com.luo.backend.controller;

import com.luo.backend.common.ApiResponse;
import com.luo.backend.dto.*;
import com.luo.backend.entity.Merchant;
import com.luo.backend.repository.MerchantRepository;
import com.luo.backend.service.ReviewService;
import com.luo.backend.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 评价控制器（用户端 + 商家端）
 */
@RestController
@RequestMapping("/api/v1")
public class ReviewController {
    
    private static final Logger logger = LoggerFactory.getLogger(ReviewController.class);
    
    @Autowired
    private ReviewService reviewService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private MerchantRepository merchantRepository;
    
    // ==================== 用户端接口 ====================
    
    /**
     * 1. 创建评价（用户端）
     * POST /api/v1/reviews
     */
    @PostMapping("/reviews")
    public ApiResponse<ReviewResponse> createReview(
            @RequestBody ReviewRequest request,
            HttpServletRequest httpRequest) {
        try {
            // 从请求头获取token并解析用户ID
            String token = httpRequest.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            logger.info("用户 {} 创建评价", userId);
            
            ReviewResponse response = reviewService.createReview(userId, request);
            return ApiResponse.success(response);
            
        } catch (Exception e) {
            logger.error("创建评价失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 2. 查询订单评价（用户端）
     * GET /api/v1/reviews/order/{orderId}
     */
    @GetMapping("/reviews/order/{orderId}")
    public ApiResponse<ReviewResponse> getOrderReview(@PathVariable Long orderId) {
        try {
            logger.info("查询订单 {} 的评价", orderId);
            
            ReviewResponse response = reviewService.getOrderReview(orderId);
            
            if (response == null) {
                return ApiResponse.error(404, "该订单暂无评价");
            }
            
            return ApiResponse.success(response);
            
        } catch (Exception e) {
            logger.error("查询订单评价失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 3. 获取用户的评价列表（用户端）
     * GET /api/v1/reviews/my
     */
    @GetMapping("/reviews/my")
    public ApiResponse<ReviewListResponse> getMyReviews(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            HttpServletRequest httpRequest) {
        try {
            // 从请求头获取token并解析用户ID
            String token = httpRequest.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            logger.info("获取用户 {} 的评价列表", userId);
            
            ReviewListResponse response = reviewService.getUserReviews(userId, page, size);
            return ApiResponse.success(response);
            
        } catch (Exception e) {
            logger.error("获取评价列表失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 4. 删除评价（用户端，24小时内）
     * DELETE /api/v1/reviews/{id}
     */
    @DeleteMapping("/reviews/{id}")
    public ApiResponse<String> deleteReview(
            @PathVariable Long id,
            HttpServletRequest httpRequest) {
        try {
            // 从请求头获取token并解析用户ID
            String token = httpRequest.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            logger.info("用户 {} 删除评价 {}", userId, id);
            
            reviewService.deleteReview(userId, id);
            return ApiResponse.success("评价删除成功");
            
        } catch (Exception e) {
            logger.error("删除评价失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 5. 商家评价列表（公开接口，不需要认证）
     * GET /api/v1/reviews/merchant/{merchantId}
     */
    @GetMapping("/reviews/merchant/{merchantId}")
    public ApiResponse<MerchantReviewPublicListResponse> getMerchantPublicReviews(
            @PathVariable Long merchantId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) Integer rating,
            @RequestParam(required = false) Boolean hasImage) {
        try {
            logger.info("获取商家 {} 的公开评价列表", merchantId);
            
            MerchantReviewPublicListResponse response = reviewService.getMerchantPublicReviews(
                    merchantId, page, size, rating, hasImage);
            return ApiResponse.success(response);
            
        } catch (Exception e) {
            logger.error("获取商家公开评价列表失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    // ==================== 商家端接口 ====================
    
    /**
     * 6. 商家回复评价（商家端）
     * POST /api/v1/merchant/reviews/{id}/reply
     */
    @PostMapping("/merchant/reviews/{id}/reply")
    public ApiResponse<ReviewResponse> replyReview(
            @PathVariable Long id,
            @RequestBody ReviewReplyRequest request,
            HttpServletRequest httpRequest) {
        try {
            // 从请求头获取token并解析用户ID
            String token = httpRequest.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 通过用户ID获取商家ID
            Merchant merchant = merchantRepository.findByOwnerUserId(userId);
            if (merchant == null) {
                return ApiResponse.error("商家信息不存在");
            }
            
            logger.info("商家 {} 回复评价 {}", merchant.getId(), id);
            
            ReviewResponse response = reviewService.replyReview(merchant.getId(), id, request.getReply());
            return ApiResponse.success(response);
            
        } catch (Exception e) {
            logger.error("回复评价失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取商家的评价列表（商家端）
     * GET /api/v1/merchant/reviews
     */
    @GetMapping("/merchant/reviews")
    public ApiResponse<MerchantReviewListResponse> getMerchantReviews(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer rating,
            @RequestParam(required = false) Boolean hasReply,
            @RequestParam(required = false) Boolean hasImage,
            HttpServletRequest httpRequest) {
        try {
            // 从请求头获取token并解析用户ID
            String token = httpRequest.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 通过用户ID获取商家ID
            Merchant merchant = merchantRepository.findByOwnerUserId(userId);
            if (merchant == null) {
                return ApiResponse.error("商家信息不存在");
            }
            
            logger.info("获取商家 {} 的评价列表", merchant.getId());
            
            MerchantReviewListResponse response = reviewService.getMerchantReviews(
                    merchant.getId(), page, size, rating, hasReply, hasImage);
            return ApiResponse.success(response);
            
        } catch (Exception e) {
            logger.error("获取商家评价列表失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取商家的评价统计（商家端）
     * GET /api/v1/merchant/reviews/statistics
     */
    @GetMapping("/merchant/reviews/statistics")
    public ApiResponse<ReviewStatisticsResponse> getMerchantReviewStatistics(
            HttpServletRequest httpRequest) {
        try {
            // 从请求头获取token并解析用户ID
            String token = httpRequest.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 通过用户ID获取商家ID
            Merchant merchant = merchantRepository.findByOwnerUserId(userId);
            if (merchant == null) {
                return ApiResponse.error("商家信息不存在");
            }
            
            logger.info("获取商家 {} 的评价统计", merchant.getId());
            
            ReviewStatisticsResponse response = reviewService.getMerchantReviewStatistics(merchant.getId());
            return ApiResponse.success(response);
            
        } catch (Exception e) {
            logger.error("获取评价统计失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
}
